package com.yh.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.ibatis.session.SqlSession;

import com.yh.dao.UserDao;
import com.yh.db.SqlSessionFactoryUtil;
import com.yh.entity.PageBean;
import com.yh.entity.User;
import com.yh.service.UserService;
import com.yh.service.impl.UserServiceImpl;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws IOException 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		 String method = request.getParameter("op");
		  if(method.equals("allUser")){
			    allUser(request,response);  
		  }else if(method.equals("modify")){
					try {
					modify(request,response);
					} catch (ParseException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}	
		  }else if(method.equals("deleteUserById")){
			  deleteUserById(request,response);
		  }else if(method.equals("queryUserId")){
			  queryUserId(request,response);
		  }else if(method.equals("modifyUserById")){
			  modifyUserById(request,response);
		  }
		
	}

	private void modifyUserById(HttpServletRequest request,HttpServletResponse response) {
		// TODO 自动生成的方法存根
	   //修改商品
		UserService userService = new UserServiceImpl();
		boolean result=userService.updateProductById(user);
		if(result){
			response.sendRedirect("html/manager/user-modify.jsp");
		}else{
			response.sendRedirect("UserServlet?op=queryUserId&u_id="+user.getU_id());
		}
	}

	//根据id查询商品
	private void queryUserId(HttpServletRequest request,HttpServletResponse response) {
		// TODO 自动生成的方法存根
		String u_id = request.getParameter("u_id");
		UserService userService = new UserServiceImpl();
		User user = null;
		if(u_id!=null){
			user = userService.queryUserById(Integer.parseInt(u_id));
		}
		//加载用户
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("html/manager/user-modify.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
	}

	private void deleteUserById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO 自动生成的方法存根
		String u_id= request.getParameter("u_id");
		UserService userService = new UserServiceImpl();
		boolean result = false;
		if(u_id!=null){
			result = userService.deleteUserById(Integer.parseInt(u_id));
		}
		if(result){
			response.getWriter().write("true");
		}else{
			response.getWriter().write("false");
		}
		
	}

	/*private void modify(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		// TODO 自动生成的方法存根
		String name = request.getParameter("name");
		String passWord = request.getParameter("passWord");
		String sex = request.getParameter("sex");
		String phone = request.getParameter("mobile");
		String birth = request.getParameter("birth");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-HH-dd ");
		int uid = Integer.parseInt(request.getParameter("id"));
		int uid = 5;
		User user = new User();
		user.setUid(uid);
		user.setUserrealname(name);
		user.setUserpwd(passWord);
		user.setUsersex(sex);
	    user.setUserbirth(new Date());
		user.setUserphone(phone);
		SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
		UserDao userDao = sqlSession.getMapper(UserDao.class);
		try{
			userDao.updateUser(user);
			response.sendRedirect(request.getContextPath()+"/html/manager/index.jsp");
		}catch(Exception e){
			e.printStackTrace();
		}
		sqlSession.commit();
		sqlSession.close();
		
	}*/

	private void allUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// TODO 自动生成的方法存根
		    String pageCode = request.getParameter("pageCode");
		    Map<String, Object> map = new HashMap<String, Object>();
		    PageBean<User> pb = new PageBean();
		    if(pageCode !=null && !"".equals("pageCode")){
		    	map.put("start", (Integer.parseInt(pageCode)-1)*pb.getPageSize());
		    	pb.setPageCode(Integer.parseInt(pageCode));
		    }else{
		    	map.put("start", 0);
		    	pb.setPageCode(1);
		    }
		    map.put("pageSize", pb.getPageSize());
		    SqlSession sqlSession = SqlSessionFactoryUtil.getSqlSession();
		    UserDao userDao = sqlSession.getMapper(UserDao.class);
		    List<User> userList = userDao.allUsers(map);
		    pb.setBeanList(userList);
		    pb.setTotalCount(userDao.countUser(map));
		    sqlSession.close();
		    response.setCharacterEncoding("UTF-8");
		    response.getWriter().write(JSONObject.fromObject(pb).toString());
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
